const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

// 获取html-webpack-plugin参数的方法
const getHtmlConfig = name => {
  return {
    template: './src/view/' + name + '.html',
    filename: name + '.html',
    inject: true,
    hash: true,
    chunks: ['common', name]
  };
};

module.exports = {
  entry: {
    index: './src/page/index/index.js',
    login: './src/page/login/index.js'
  },

  output: {
    filename: 'js/[name].js',
    path: path.resolve(__dirname, 'dist')
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader?cacheDirectory=true',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.css$/, // 正则匹配以.css结尾的文件
        use: ExtractTextPlugin.extract({
          // 这里我们需要调用分离插件内的extract方法
          fallback: 'style-loader', // 相当于回滚，经postcss-loader和css-loader处理过的css最终再经过style-loader处理
          use: ['css-loader', 'postcss-loader'],
          publicPath: '../' // 给背景图片设置一个公共路径
        })
      },
      {
        test: /\.(png|jpg|svg|gif|woff|eot|ttf)$/, // 正则匹配图片格式名
        use: [
          {
            loader: 'url-loader', // 使用url-loader
            options: {
              limit: 1000, // 限制只有小于1kb的图片才转为base64
              outputPath: 'images' // 设置打包后图片存放的文件夹名称
            }
          }
        ]
      }
    ]
  },

  plugins: [
    new HtmlWebpackPlugin(getHtmlConfig('index')),
    new HtmlWebpackPlugin(getHtmlConfig('login')),
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin('css/index.css') // 将css分离到/dist文件夹下的css文件夹中的index.css
  ]
};
